package com.eudi.springmvc.controller.log;

import java.util.Date;
import java.util.Enumeration;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/log")
public class LogController {
	private static Logger logger = Logger.getLogger(LogController.class);
	
	@RequestMapping(value = "/{l}", method = RequestMethod.GET)
	public @ResponseBody String modifyRoot(@PathVariable String l) {
		Level level = Level.toLevel(l);
		Logger logger = LogManager.getRootLogger();
		logger.info("修改日志级别，级别:" + l + ", 原级别:" + logger.getLevel());
		
		logger.setLevel(level);
		
		return logger.getName() + logger.getLevel();
	}
	
	@RequestMapping(value = "/appender/{a}/{l}")
	public @ResponseBody String modifyAppender(@PathVariable String l, @PathVariable String a) {
		Level level = Level.toLevel(l);
		Logger logger = LogManager.getRootLogger();
		AppenderSkeleton appender = (AppenderSkeleton) logger.getAppender(a);
		logger.info("修改" + a + "日志级别,级别:" + l + ",原级别:" + appender.getThreshold());
		appender.setThreshold(level);
		return appender.getName() + ":" + appender.getThreshold();
	}
	
	@RequestMapping(value = "/{p}/{l}")
	public @ResponseBody String modifyPackage(@PathVariable String l, @PathVariable String p) {
		Level level = Level.toLevel(l);
		Logger logger = LogManager.getLogger("p");
		logger.info("修改日志级别, 包:" + p + ",级别:" + l + ",原级别:" + logger.getLevel());
		logger.setLevel(level);

		StringBuffer sb = new StringBuffer();
		Enumeration<Logger> logs = LogManager.getCurrentLoggers();
		while(logs.hasMoreElements()) {
			Logger log = logs.nextElement();
			if(log.getName().startsWith("com.eudi")) {
				sb.append(log.getName()).append(":").append(LogManager.getRootLogger().getLevel());
			}
		}
		
		sb.append(LogManager.getRootLogger().getName()).append(LogManager.getRootLogger().getLevel()).append("<br>");
		sb.append(logger.getName()).append(":").append(logger.getLevel());
		
		return sb.toString();
	}
	
	public LogController() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				while(true) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					logger.info(new Date());
				}
				
			}}).start();
	}
}
